import React, { useState, useEffect } from 'react';
import { Layout, Menu, Row, Col, Card, Tag, Button, Avatar, Typography, Space, Spin, message } from 'antd';
import {
  MessageOutlined,
  DollarOutlined,
  TeamOutlined,
  CalendarOutlined,
  BarChartOutlined,
  SettingOutlined,
  ToolOutlined,
  ExperimentOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  BankOutlined,
  NotificationOutlined,
  TrophyOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  PhoneOutlined,
  LogoutOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { authService } from '../lib/authService';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { localChatWebSocketService as chatWebSocketService, type WebSocketMessage } from '../lib/localWebSocketService';
import { useCustomers } from '../hooks/useCustomers';
import { getCustomerPriority, getCustomerTags } from '../utils/customerMapping';
import { filterCustomersByRole } from '../utils/customerFilter';
import ToolsLibraryPage from './ToolsLibraryPage';
import StrategyAnalyticsDashboard from './StrategyAnalyticsDashboard';
import { customerService } from '../services/customerService';
import { useCustomerContext } from '../context/CustomerContext';
import { formatNumber } from '../utils/numberFormat';
import { getCustomerAvatar } from '../utils/avatarUtils';
import { getTimeAgo } from '../utils/timeUtils';
import { localChatStorage ,type LocalConversationState} from '../lib/localChatStorage';

const { Title, Text } = Typography;
const { Sider, Content } = Layout;

// 会话数据接口
interface ConversationData {
  id: string;
  customer: any; // 客户完整数据
  priority: 'high' | 'medium' | 'low';
  lastMessage: string;
  status: string;
  tags: string[];
  waitingTime: string;
  unreadCount: number;
  lastMessageTime?: number;
  conversationId: string; // 后端会话ID
}

// 侧边菜单项
const menuItems = [
  {
    key: 'model-day',
    icon: <CalendarOutlined />,
    label: '工作台',
  },
  {
    key: 'tools-library',
    icon: <ToolOutlined />,
    label: '常用工具库',
  },
  {
    key: 'analytics',
    icon: <BarChartOutlined />,
    label: '数据分析',
  },
  {
    key: 'settings',
    icon: <SettingOutlined />,
    label: '设置',
  }
];

// Model Day 组件
const ModelDayContent = () => {
  const [conversations, setConversations] = useState<ConversationData[]>([]);
  const [isConnected, setIsConnected] = useState(false);
  const navigate = useNavigate();

  // 使用客户数据Hook
  const { customers } = useCustomers();
  
  // 获取当前管理员信息
  const currentManager = authService.getManager();

  // 使用客户上下文
  const { setSelectedCustomer } = useCustomerContext();

  // 设置中文
  dayjs.locale('zh-cn');

  // 将用户信息转换为前端ConversationData格式
  const convertUserToConversationData = (customer: any): ConversationData => {
     // 从localStorage获取conversation state
     const conversationStates = localChatStorage.getConversations();
     const customerId = customerService.getCustomerWebSocketId(customer); // 使用统一的WebSocket用户ID格式
     const conversationState = conversationStates.find((cs: LocalConversationState) => cs.c_user_id === customerId);

    const lastMessageTime = conversationState ? new Date(conversationState.last_message_time.endsWith('Z') ? conversationState.last_message_time : conversationState.last_message_time + 'Z').getTime() : 0;

    return {
      id: customer.id.toString(),
      customer: customer,
      priority: getCustomerPriority(customer),
      lastMessage: conversationState?.last_message_content || '等待客户发送消息...',
      status: conversationState && conversationState.b_user_unread_count > 0 ? '等待回复' : '在线等待',
      tags: getCustomerTags(customer),
      waitingTime: getTimeAgo(lastMessageTime),
      unreadCount: conversationState?.b_user_unread_count || 0,
      lastMessageTime: lastMessageTime,
      conversationId: conversationState?.conversation_id || `conv_${customer.id.toString()}`
    };
  };


  useEffect(() => {
    // 检查WebSocket连接状态
    const checkConnection = () => {
      setIsConnected(chatWebSocketService.isConnected());
    };

    // 定时检查连接状态
    const connectionCheckInterval = setInterval(checkConnection, 2000);

    // 消息监听器
    const handleWebSocketMessage = (wsMessage: WebSocketMessage) => {

              if (wsMessage.type === 'message' && wsMessage.sender_id) {
          // 检查是否是C端用户发来的消息（不是B端用户发的）
          if (wsMessage.sender_id && !wsMessage.sender_id.startsWith('B_')) {
            // C端用户发来消息，显示通知
            const clientInfo = customerService.getCustomerById(wsMessage.sender_id);
          const customerName = clientInfo?.name || wsMessage.sender_id;
          const content = wsMessage.content || '';
          message.info(`收到来自${customerName}的新消息: ${content.substring(0, 20)}${content.length > 20 ? '...' : ''}`);

          // 重新加载会话状态以确保显示最新数据
          setTimeout(() => {
            try {
              // 直接更新本地状态，不调用远程API
              setConversations(prev => {
                return prev.map(conv => {
                  if (conv.id === wsMessage.sender_id) {
                    return {
                      ...conv,
                      lastMessage: content.substring(0, 50) + (content.length > 50 ? '...' : ''),
                      unreadCount: conv.unreadCount + 1,
                      status: '等待回复',
                      lastMessageTime: Date.now(),
                      waitingTime: '刚刚'
                    };
                  }
                  return conv;
                });
              });
            } catch (error) {
              console.warn('Failed to update conversations after message:', error);
            }
          }, 300);
        }
      }
    };

    // 会话更新监听器（简化版，仅用于本地数据）
    const handleConversationUpdate = () => {
      // 使用Hook中的客户数据
      let allCustomers = customers;
      // 根据用户角色过滤客户列表
      allCustomers = filterCustomersByRole(allCustomers, currentManager?.name);

      // 为所有客户生成对话数据
      const allConversations = allCustomers.map(customer => {
        return convertUserToConversationData(customer);
      });

      // 按最后消息时间排序，杨丽置顶
      allConversations.sort((a, b) => {
        // 硬置顶：杨丽永远在最前面
        if (a.customer.name === '杨丽') return -1;
        if (b.customer.name === '杨丽') return 1;
        
        // 其他客户按最后消息时间排序（最新的在前）
        return (b.lastMessageTime || 0) - (a.lastMessageTime || 0);
      });

      setConversations(allConversations);
    };

    // 注册监听器
    chatWebSocketService.addMessageListener(handleWebSocketMessage);
    chatWebSocketService.addConversationUpdateListener(handleConversationUpdate);

    // 初始加载会话数据
    const loadInitialConversations = async () => {
      try {
        // 使用Hook中的客户数据
        let allCustomers = customers;
        
        // 根据用户角色过滤客户列表
        allCustomers = filterCustomersByRole(allCustomers, currentManager?.name);
        
        const initialConversations = allCustomers.map(customer =>
          convertUserToConversationData(customer)
        );

        // 按最后消息时间排序，杨丽置顶
        initialConversations.sort((a, b) => {
          // 硬置顶：杨丽永远在最前面
          if (a.customer.name === '杨丽') return -1;
          if (b.customer.name === '杨丽') return 1;
          
          // 其他客户按最后消息时间排序（最新的在前）
          return (b.lastMessageTime || 0) - (a.lastMessageTime || 0);
        });

        setConversations(initialConversations);

        // 使用本地数据，不需要调用远程API
        console.log('Using local conversation data without remote API calls');
      } catch (error) {
        console.error('Failed to load initial conversations:', error);
      }
    };

    // 等待WebSocket连接成功后再加载数据
    const waitForConnectionAndLoad = () => {
      if (chatWebSocketService.isConnected()) {
        loadInitialConversations();
      } else {
        // 每2秒检查一次连接状态，最多等待20秒
        let attempts = 0;
        const checkConnectionInterval = setInterval(() => {
          attempts++;
          if (chatWebSocketService.isConnected()) {
            clearInterval(checkConnectionInterval);
            loadInitialConversations();
          } else if (attempts >= 10) {
            clearInterval(checkConnectionInterval);
            console.warn('WebSocket connection timeout, loading conversations anyway');
            loadInitialConversations();
          }
        }, 2000);
      }
    };

    // 当客户数据加载完成后，初始化会话数据
    if (customers.length > 0) {
      waitForConnectionAndLoad();
    }

    // 定时更新等待时间
    const updateTimeInterval = setInterval(() => {
      setConversations(prevConversations => {
        return prevConversations.map(conv => {
          if (conv.lastMessageTime) {
            return {
              ...conv,
              waitingTime: getTimeAgo(conv.lastMessageTime)
            };
          }
          return conv;
        });
      });
    }, 60000); // 每分钟更新一次

    // 清理函数
    return () => {
      clearInterval(connectionCheckInterval);
      clearInterval(updateTimeInterval);
      chatWebSocketService.removeMessageListener(handleWebSocketMessage);
      chatWebSocketService.removeConversationUpdateListener(handleConversationUpdate);
    };
  }, [customers]); // 依赖customers，当客户数据更新时重新初始化

  // 计算指标数据
  const metrics = React.useMemo(() => {

    return {
      totalClients: conversations.length,
      activeConversations: conversations.filter(c => c.status === '等待回复' || c.status === '在线等待').length,
      totalValue: conversations.reduce((sum: number, c: ConversationData) => sum + (c.customer.total_investment ?? 0), 0),
      unreadMessages: conversations.reduce((sum: number, c: ConversationData) => sum + c.unreadCount, 0)
    };
  }, [conversations]);

  const handleConversationClick = async (conversationData: ConversationData) => {
    // 标记为已读
    if (conversationData.unreadCount > 0) {
      try {
        await chatWebSocketService.markConversationRead(conversationData.conversationId);

        // 更新本地状态
        setConversations(prevConversations => {
          return prevConversations.map(conv => {
            if (conv.id === conversationData.id) {
              return {
                ...conv,
                unreadCount: 0,
                status: '已读'
              };
            }
            return conv;
          });
        });
      } catch (error) {
        console.error('Failed to mark conversation as read:', error);
      }
    }

    // 直接使用conversationData中的customer数据
    if (conversationData.customer) {
      setSelectedCustomer(conversationData.customer);
    }

    // 导航到会话页面
    navigate(`/conversation`);
  };



  if (!customers || customers.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen">
        <Spin size="large" />
        <div className="mt-3 text-gray-600">加载数据中...</div>
      </div>
    );
  }

  return (
    <div className="dashboard-layout">
      <div className="dashboard-header">
        <div className="dashboard-header-content">
          <div className="dashboard-title-section">
            <Title level={2} className="!mb-1 text-gray-800" style={{ fontSize: '20px', lineHeight: '1.2' }}>欢迎回来{currentManager?.name ? `，${currentManager.name}` : ''}！</Title>
          </div>
          <div className="dashboard-button-section">
            <Space size="small">
              <Button
                type="default"
                icon={<ExperimentOutlined />}
                size="middle"
                className="border-blue-500 text-blue-500 hover:bg-blue-50 shadow-sm rounded-lg"
                onClick={() => window.open('/client-test', '_blank')}
              >
                模拟测试
              </Button>
              <Button
                type="default"
                icon={<LogoutOutlined />}
                size="middle"
                className="border-red-500 text-red-500 hover:bg-red-50 shadow-sm rounded-lg"
                onClick={() => {
                  authService.logout();
                  message.success('已退出登录');
                  navigate('/login');
                }}
              >
                注销登录
              </Button>
            </Space>
          </div>
        </div>
      </div>

      <div className="dashboard-content">
        {/* 关键指标卡片 - 紧凑设计 */}
        <div className="dashboard-metrics">
          <Row gutter={[12, 12]}>
            <Col xs={12} sm={6} lg={6}>
              <Card
                className="metric-card metric-card-green"
                hoverable
                styles={{ body: { padding: '16px' } }}
                size="small"
              >
                <div className="metric-content">
                  <div className="metric-icon" style={{ fontSize: '20px' }}>
                    <TeamOutlined />
                  </div>
                  <div className="metric-info">
                    <div className="metric-title" style={{ fontSize: '12px', marginBottom: '4px' }}>客户总数</div>
                    <div className="metric-value" style={{ fontSize: '24px', lineHeight: '1.2' }}>{metrics.totalClients}</div>
                    <div className="metric-status" style={{ fontSize: '11px' }}>
                      <span className={`status-dot ${isConnected ? 'online' : 'offline'}`}></span>
                      {isConnected ? '系统在线' : '系统离线'}
                    </div>
                  </div>
                </div>
              </Card>
            </Col>
            <Col xs={12} sm={6} lg={6}>
              <Card
                className="metric-card metric-card-blue"
                hoverable
                styles={{ body: { padding: '16px' } }}
                size="small"
              >
                <div className="metric-content">
                  <div className="metric-icon" style={{ fontSize: '20px' }}>
                    <MessageOutlined />
                  </div>
                  <div className="metric-info">
                    <div className="metric-title" style={{ fontSize: '12px', marginBottom: '4px' }}>活跃会话</div>
                    <div className="metric-value" style={{ fontSize: '24px', lineHeight: '1.2' }}>{metrics.activeConversations}</div>
                    <div className="metric-subtitle" style={{ fontSize: '11px' }}>正在进行的对话</div>
                  </div>
                </div>
              </Card>
            </Col>
            <Col xs={12} sm={6} lg={6}>
              <Card
                className="metric-card metric-card-orange"
                hoverable
                styles={{ body: { padding: '16px' } }}
                size="small"
              >
                <div className="metric-content">
                  <div className="metric-icon" style={{ fontSize: '20px' }}>
                    <NotificationOutlined />
                  </div>
                  <div className="metric-info">
                    <div className="metric-title" style={{ fontSize: '12px', marginBottom: '4px' }}>未读消息</div>
                    <div className="metric-value" style={{ fontSize: '24px', lineHeight: '1.2' }}>{metrics.unreadMessages}</div>
                    <div className="metric-subtitle" style={{ fontSize: '11px' }}>待处理消息</div>
                  </div>
                </div>
              </Card>
            </Col>
            <Col xs={12} sm={6} lg={6}>
              <Card
                className="metric-card metric-card-purple"
                hoverable
                styles={{ body: { padding: '16px' } }}
                size="small"
              >
                <div className="metric-content">
                  <div className="metric-icon" style={{ fontSize: '20px' }}>
                    <DollarOutlined />
                  </div>
                  <div className="metric-info">
                    <div className="metric-title" style={{ fontSize: '12px', marginBottom: '4px' }}>总资产管理</div>
                    <div className="metric-value" style={{ fontSize: '24px', lineHeight: '1.2' }}>{formatNumber(metrics.totalValue)}万</div>
                    <div className="metric-subtitle" style={{ fontSize: '11px' }}>资产规模</div>
                  </div>
                </div>
              </Card>
            </Col>
          </Row>
        </div>

        {/* 今日任务板块 - 紧凑设计 */}
        <div className="dashboard-tasks">
          <Card
            className="task-card"
            title={
              <div className="card-header" style={{ height: '32px', display: 'flex', alignItems: 'center' }}>
                <div className="header-left" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <TrophyOutlined className="header-icon" style={{ fontSize: '16px' }} />
                  <span className="header-title" style={{ fontSize: '14px', fontWeight: '500' }}>今日任务</span>
                  <span className="task-count" style={{ fontSize: '12px', background: '#f0f0f0', padding: '2px 6px', borderRadius: '10px' }}>3</span>
                </div>
                <a href="#tasks" className="header-link" style={{ fontSize: '12px', marginLeft: 'auto' }}>管理任务</a>
              </div>
            }
            styles={{ body: { padding: '16px' } }}
            size="small"
          >
            <Row gutter={[12, 12]}>
              <Col xs={24} md={8}>
                <div className="task-item task-urgent" style={{ padding: '12px', borderRadius: '6px', border: '1px solid #ffeaa7', backgroundColor: '#fff9e6' }}>
                  <div className="task-info" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <ExclamationCircleOutlined className="task-icon" style={{ fontSize: '14px', color: '#fa8c16' }} />
                    <span className="task-text" style={{ fontSize: '13px', flex: 1 }}>跟进高优先级客户</span>
                  </div>
                  <span className="task-badge urgent" style={{ fontSize: '11px', padding: '2px 6px', borderRadius: '10px', backgroundColor: '#fa8c16', color: 'white', marginTop: '4px', display: 'inline-block' }}>紧急</span>
                </div>
              </Col>
              <Col xs={24} md={8}>
                <div className="task-item task-important" style={{ padding: '12px', borderRadius: '6px', border: '1px solid #b7e5ff', backgroundColor: '#f6ffff' }}>
                  <div className="task-info" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <CheckCircleOutlined className="task-icon" style={{ fontSize: '14px', color: '#1890ff' }} />
                    <span className="task-text" style={{ fontSize: '13px', flex: 1 }}>完成客户风险评估</span>
                  </div>
                  <span className="task-badge important" style={{ fontSize: '11px', padding: '2px 6px', borderRadius: '10px', backgroundColor: '#1890ff', color: 'white', marginTop: '4px', display: 'inline-block' }}>重要</span>
                </div>
              </Col>
              <Col xs={24} md={8}>
                <div className="task-item task-normal" style={{ padding: '12px', borderRadius: '6px', border: '1px solid #d9f7be', backgroundColor: '#f9fff9' }}>
                  <div className="task-info" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <BarChartOutlined className="task-icon" style={{ fontSize: '14px', color: '#52c41a' }} />
                    <span className="task-text" style={{ fontSize: '13px', flex: 1 }}>更新产品推荐列表</span>
                  </div>
                  <span className="task-badge normal" style={{ fontSize: '11px', padding: '2px 6px', borderRadius: '10px', backgroundColor: '#52c41a', color: 'white', marginTop: '4px', display: 'inline-block' }}>一般</span>
                </div>
              </Col>
            </Row>
          </Card>
        </div>
      </div>

      {/* 高潜客户列表 - 卡片式设计 */}
      <div className="dashboard-conversations">
        <Card
          className="conversation-card"
          title={
            <div className="card-header">
              <div className="header-left">
                <MessageOutlined className="header-icon" />
                <span className="header-title">高潜客户列表</span>
                <span className="conversation-count">{conversations.length}</span>
              </div>
            </div>
          }
          styles={{ body: { padding: '24px' } }}
        >
          <div className="customer-cards-container">
            <Row gutter={[16, 16]}>
              {conversations.map((conversation, index) => (
                <Col key={conversation.id} xs={24} sm={12} md={8} lg={8} xl={8}>
                  <Card
                    className="customer-info-card"
                    styles={{ body: { padding: '24px' } }}
                    style={{ animationDelay: `${index * 0.1}s` }}
                  >
                    {/* 客户基本信息头部 */}
                    <div className="customer-header">
                      <div className="customer-avatar-section">
                        <Avatar
                          size={48}
                          src={getCustomerAvatar(conversation.customer.id || 0, conversation.customer.name)}
                          className="customer-avatar"
                        />
                        <div className="customer-basic-info">
                          <div className="customer-name">{conversation.customer.name}</div>
                          <div className="customer-tags">
                            {conversation.tags?.map((tag: string) => (
                              <Tag key={tag} color="blue" className="tag-small">
                                {tag}
                              </Tag>
                            ))}
                          </div>
                        </div>
                      </div>
                      <div className="customer-status">
                        <div className="status-section">
                          <div className="status-date">
                            {conversation.unreadCount > 0 ? '今日未接听' : '今日已接听'}
                          </div>
                          {conversation.unreadCount > 0 && (
                            <div className="unread-badge">
                              <span className="unread-count">+{conversation.unreadCount}</span>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>

                    {/* KYC小结 */}
                    <div className="kyc-summary">
                      <div className="kyc-title">KYC小结</div>
                      <div className="kyc-content">{
                        (() => {
                          let summaryText = '';
                          try {
                            const ai = JSON.parse(conversation.customer.ai_summary || '{}');
                            if (typeof ai === 'object' && ai !== null) {
                              summaryText = Object.entries(ai)
                                .map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join('、') : v}`)
                                .join('；');
                            }
                          } catch (e) {
                            summaryText = conversation.customer.ai_summary || '';
                          }
                          return summaryText.length > 75 ? summaryText.slice(0, 75) + '…' : summaryText;
                        })()
                      }</div>
                    </div>

                    {/* 线索信息 */}
                    <div className="clue-info" style={{ height: '90px', display: 'flex', flexDirection: 'column' }}>
                      <div className="clue-title">线索信息</div>
                      {conversation.customer.name === '杨丽' && (
                        <div className="clue-content">近日产品到期</div>
                      )}
                    </div>

                    {/* 底部操作按钮 */}
                    <div className="customer-actions">
                      <Button
                        type="default"
                        size="small"
                        icon={<PhoneOutlined />}
                        className="action-btn call-btn"
                        disabled
                      >
                        外呼
                      </Button>
                      <Button
                        type="primary"
                        size="small"
                        icon={<MessageOutlined />}
                        className="action-btn im-btn"
                        onClick={() => handleConversationClick(conversation)}
                      >
                        IM
                      </Button>
                    </div>

                    {/* 等待时间指示器 */}
                    <div className="waiting-time-indicator" style={{ minHeight: '24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
                      {conversation.waitingTime ? (
                        <span className="waiting-time" style={{ minHeight: '20px', display: 'flex', alignItems: 'center' }}>
                        {conversation.waitingTime}
                      </span>
                      ) : (
                        <span style={{ minHeight: '24px', display: 'flex', alignItems: 'center' }}></span>
                      )}
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>

            {conversations.length === 0 && (
              <div className="empty-state">
                <Text type="secondary">暂无客户数据</Text>
              </div>
            )}
          </div>
        </Card>
      </div>
    </div>
  );
};

export default function Dashboard() {
  const navigate = useNavigate();
  const [collapsed, setCollapsed] = useState(false);

  // 根据当前路径确定选中的菜单项
  const getSelectedKeyFromPath = (pathname: string) => {
    if (pathname === '/model-day') return 'model-day';
    if (pathname === '/tools-library') return 'tools-library';
    if (pathname === '/analytics') return 'analytics';
    if (pathname === '/settings') return 'settings';
    return 'model-day'; // 默认值
  };

  const selectedKey = getSelectedKeyFromPath(window.location.pathname);

  const renderContent = () => {
    switch (selectedKey) {
      case 'model-day':
        return <ModelDayContent />;
      case 'analytics':
        return <StrategyAnalyticsDashboard />;
      case 'settings':
        return (
          <div className="p-6">
            <Title level={2}>设置</Title>
            <Card>
              <p>设置功能正在开发中...</p>
            </Card>
          </div>
        );
      case 'tools-library':
        return <ToolsLibraryPage />;
      default:
        return <ModelDayContent />;
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={setCollapsed}
        width={240}
        collapsedWidth={80}
        style={{ background: '#fff' }}
        className="shadow-lg"
        trigger={null}
      >
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
          {/* Logo 和标题区域 */}
          <div className={`p-4 border-b border-gray-200 flex items-center gap-3 ${collapsed ? 'justify-center' : ''}`}>
            <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-lg flex items-center justify-center text-white font-bold text-lg shadow-md">
              <BankOutlined />
            </div>
            {!collapsed && (
              <div>
                <Title level={4} className="!mb-0 !text-gray-800">理财师 Copilot</Title>
                <Text type="secondary" className="text-xs">智能投顾助手</Text>
              </div>
            )}
          </div>

          <Menu
            mode="inline"
            selectedKeys={[selectedKey]}
            onClick={({ key }) => navigate(`/${key}`)}
            items={menuItems}
            className="border-none bg-white"
            style={{ flex: 1, borderRight: 'none' }}
            inlineIndent={collapsed ? 0 : 24}
          />

          {/* 折叠按钮 - 移到底部 */}
          <div className="p-2 border-t border-gray-100">
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              className="w-full flex items-center justify-center hover:bg-blue-50"
            />
          </div>
        </div>
      </Sider>
      <Layout>
        <Content style={{ background: '#fff' }}>
          {renderContent()}
        </Content>
      </Layout>
    </Layout>
  );
}
